<?php
namespace App\Component;

use App\Core\Exception\DefaultException;
use EasySwoole\Component\Singleton;
use EasySwoole\Curl\Field;
use EasySwoole\Curl\Request;
use EasySwoole\Curl\Response;

class Curl
{

    use Singleton;

    public function __construct(){

    }

    /**
     * @param string $method
     * @param string $url
     * @param array $params
     * @param array $header
     */
    public function request( string $method, string $url, array $params = null ,array $header =[]) : Response
    {
        $request = new Request( $url );
        switch( $method ){
            case 'GET' :
                if( !empty($params) ){
                    foreach( $params as $key => $value ){
                        $request->addGet( new Field( $key, $value ) );
                    }
                }
                break;
            case 'POST' :
                if( !empty($params)  ){
                    foreach( $params as $key => $value ){
                        $request->addPost( new Field( $key, $value ) );
                    }
                }
                //$request->setUserOpt( [CURLOPT_POSTFIELDS => $params['body']] );
                break;
            default:
                throw new DefaultException('method eroor！');
                break;
        }
        if( !empty($header) ){
            $headers = [];
            foreach( $header as $key => $value ){
                $string = "{$key}:$value";
                $headers[] = $string;
            }
            $request->setUserOpt( [CURLOPT_HTTPHEADER => $header] );
        }
        return $request->exec();
    }

}